<template>
  <div>
    <Card _Title="售后详情" :_Size="16"></Card>
    <a-card bordered :body-style="bodyStyle"
            v-if="(afterSale.serviceStatus == 'PASS' && afterSale.serviceType != 'RETURN_MONEY') || (afterSale.afterSaleAllowOperationVO && afterSale.afterSaleAllowOperationVO.cancel)">
      <a-button status="warning" type="outline" size="small" class="mr_10" @click="handleReceived(afterSale.sn)"
                v-if="afterSale.serviceStatus == 'PASS' && afterSale.serviceType != 'RETURN_MONEY'">提交物流</a-button>
      <a-button status="danger" type="primary" size="small" class="mr_10" @click="handleCancelOrder(afterSale.sn)"
                v-if="afterSale.afterSaleAllowOperationVO && afterSale.afterSaleAllowOperationVO.cancel">取消售后</a-button>
    </a-card>
    <div class="order-card">
      <h3>{{afterSale.serviceName}}</h3>
      <div class="global-color fontsize-18 mt_20">{{ afterSale.orderStatusValue }}</div>
      <div class="flex mt_10" style="justify-content: space-between;">
        <div class="light-text-color">售后单号：{{ afterSale.sn }}&nbsp;&nbsp;&nbsp;订单号：{{afterSale.orderSn}}</div>
        <div class="light-text-color">创建时间：{{afterSale.createTime}}</div>
      </div>
      <div class="service-after mt_10 mb_10 ml_10 mr_10 flex">
        <div>本次售后服务由<span>{{afterSale.storeName}}</span>为您提供</div>
        <div>
          <a-image :src="afterSale.goodsImage" alt="" width="60" height="60" />
          <span class="ml_10">{{afterSale.goodsName}}</span>
        </div>
      </div>
    </div>
    <!--售后进程-->
    <div class="order-card" style="border-top: 1px solid #eeeeee;border-bottom: 1px solid #eeeeee;">
      <h3>售后进程</h3>
      <div class="steps-box mt_20 mb_20">
        <a-steps small direction="vertical" :current="logList.length+1">
          <a-step :description="'操作人：'+log.operatorName+' '+log.createTime" v-for="(log, index) in logList" :key="index">{{log.message}}</a-step>
        </a-steps>
      </div>
    </div>
    <!--服务单信息-->
    <div class="order-card">
      <h3>服务单信息</h3>
      <div class="reason-list">
        <div><span>退款方式</span><span>{{afterSale.refundWay == 'ORIGINAL' ? '原路退回' : '账号退款'}}</span></div>
        <div><span>申请退款金额</span><span>{{unitPrice(afterSale.applyRefundPrice, '￥')}}</span></div>
        <div v-if="afterSale.actualRefundPrice"><span>实际退款金额</span><span>{{unitPrice(afterSale.actualRefundPrice, '￥')}}</span></div>
        <template v-if="afterSale.refundWay === 'OFFLINE'">
          <div><span>退款开户行</span><span>{{afterSale.bankDepositName}}</span></div>
          <div><span>退款开户名</span><span>{{afterSale.bankAccountName}}</span></div>
          <div><span>退款卡号</span><span>{{afterSale.bankAccountNumber}}</span></div>
        </template>
        <div><span>商品处理方式</span><span>{{afterSale.serviceType == 'RETURN_MONEY' ? '退款' : '退货'}}</span></div>
        <div><span>退款原因</span><span>{{afterSale.reasonName}}</span></div>
        <div><span>问题描述</span><span>{{afterSale.problemDesc}}</span></div>
      </div>
    </div>
    <!--图片信息-->
    <div class="order-card" v-if="afterSale.afterSaleImage">
      <h3>图片信息</h3>
      <div v-for="img in afterSale.afterSaleImage.split(',')" :key="img" style="display: inline-block;" class="mr_10 mb_10">
        <a-image :src="img" width="100" height="100" alt="" />
      </div>
    </div>
    <!--商家退货地址-->
    <!--如果服务类型为退款则不显示-->
    <div class="order-card" v-if="afterSale.serviceType !== 'RETURN_MONEY' && afterSale.serviceStatus !== 'APPLY'">
      <h3>商家退货信息</h3>
      <div class="reason-list">
        <div><span>联系人</span><span>{{storeAfterSaleAddress.salesConsigneeName}}</span></div>
        <div><span>联系方式</span><span>{{storeAfterSaleAddress.salesConsigneeMobile}}</span></div>
        <div>
          <span>收货地址</span>
          <span>
            <template v-if="storeAfterSaleAddress.salesConsigneeAddressPath">{{storeAfterSaleAddress.salesConsigneeAddressPath}}</template>
            <template v-if="storeAfterSaleAddress.salesConsigneeDetail">{{storeAfterSaleAddress.salesConsigneeDetail}}</template>
          </span>
        </div>
      </div>
    </div>
    <!--提交物流信息-->
    <a-modal v-model:visible="logisticsModal" width="600px" top="100">
      <template #title>提交物流信息</template>
      <a-form ref="logisticsRef" :model="logisticsForm" size="large" layout="horizontal" auto-label-width :style="{ width: '400px'}" class="mt_20">
        <a-form-item field="logisticsId" label="物流公司" :rules="[REQUIRED]">
          <a-select :style="{width:'320px'}" placeholder="" v-model="logisticsForm.logisticsId">
            <a-option v-for="item in companyList" :value="item.id" :key="item.id">{{item.name}}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="logisticsNo" label="物流单号" :rules="[REQUIRED]">
          <a-input v-model="logisticsForm.logisticsNo" allow-clear placeholder="请填写物流单号" :style="{width:'320px'}"></a-input>
        </a-form-item>
        <a-form-item field="mDeliverTime" label="发货时间" :rules="[REQUIRED]">
          <a-date-picker type="date" v-model="logisticsForm.mDeliverTime" placeholder="请选择发货时间" :style="{width:'320px'}" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="logisticsModal = false">取消</a-button>
        <a-button @click="handleSubmit" status="danger" type="primary" :loading="loading">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { useRoute } from 'vue-router';
  import { ref, onMounted } from 'vue';
  import { afterSaleStatusList } from '../enumeration.js';
  import { unitPrice } from '@/utils/filters';
  import { REQUIRED } from '@/utils/validator';
  import { Message, Modal } from '@arco-design/web-vue';
  import { afterSaleDetail, afterSaleLog, afterSaleReason, cancelAfterSale } from '@/api/member';
  import { afterSaleDelivery, getLogisticsCompany, getStoreAfterSaleAddress } from '@/api/order';

  const route = useRoute();
  const loading = ref(false);
  const afterSale = ref<any>({});  // 售后详情数据
  const logList = ref<Array<any>>([]);  // 日志
  const reasonList = ref([]);  // 售后原因列表
  const logisticsModal = ref(false);  // 提交物流信息modal
  const logisticsRef = ref(); // 物流信息表单ref
  const logisticsForm = ref({
    afterSaleSn: '',
    logisticsId: '',
    logisticsNo: '',
    mDeliverTime: ''
  }); // 物流信息表单
  const companyList = ref(); // 物流公司列表
  const bodyStyle = ref({border: 'none'});
  const storeAfterSaleAddress = ref<any>({});


  // 获取商家售后收件地址
  const getAddress = () => {
    getStoreAfterSaleAddress(route.query.sn).then(res => {
      if (res.data.success) {
        storeAfterSaleAddress.value = res.data.result;
      }
    })
  };

  const getDetail = () => { // 售后详情
    afterSaleDetail(route.query.sn).then(res => {
      if (res.data.success) {
        afterSale.value = res.data.result;
        afterSale.value.serviceName = filterOrderStatus(afterSale.value.serviceStatus);
        // 如果是原因id，则调接口查询原因中文释义
        const pattern3 = new RegExp('[0-9]+');
        if (pattern3.test(afterSale.value.reason)) {
          getReason(afterSale.value.serviceType)
        } else {
          afterSale.value.reasonName = afterSale.value.reason;
        }
      }
    });
    getAddress();
  };
  // 获取售后原因
  const getReason = (type: any) => {
    afterSaleReason(type).then(res => {
      if (res.data.success) {
        reasonList.value = res.data.result;
        reasonList.value.forEach((e: any) => {
          if (e.id === afterSale.value.reason) {
            afterSale.value.reasonName = e.reason;
          }
        })
      }
    })
  };
  // 获取售后日志
  const getLog = () => {
    afterSaleLog(route.query.sn).then(res => {
      if (res.data.success) logList.value = res.data.result;
    })
  };
  // 获取订单状态中文
  const filterOrderStatus = (status: any) => {
    const ob = afterSaleStatusList.filter(e => { return e.status === status });
    if (ob.length) return ob[0].name
  };
  // 获取物流公司列表
  const getCompany = () => {
    getLogisticsCompany().then(res => {
      if (res.data.success) {
        companyList.value = res.data.result;
      }
    })
  };

  // 提交物流modal
  const handleReceived = (sn: any) => {
    logisticsForm.value.afterSaleSn = sn;
    logisticsModal.value = true;
    if (!companyList.value || !companyList.value.length) {
      getCompany();
    }
  };
  // 提交物流信息
  const handleSubmit = async () => {
      const auth = await logisticsRef.value?.validate();
    if (!auth) {
      loading.value = true;
      afterSaleDelivery(logisticsForm.value).then(res => {
        if (res.data.success) {
          logisticsModal.value = false;
          Message.success('提交成功');
          getDetail();
          getLog();
        }
        loading.value = false;
      }).catch(() => {
        loading.value = false;
      })
    }
  };

  // 取消售后
  const handleCancelOrder = (sn: any) => {
    Modal.confirm({
      title: '取消售后',
      content: `确定取消此次售后申请吗？`,
      okButtonProps: {
        type: "primary",
        status: "danger"
      },
      onOk: () => {
        cancelAfterSale(sn).then(res => {
          if (res.data.success) {
            Message.success('取消售后申请成功');
            getDetail();
            getLog();
          }
        })
      }
    })
  };

  onMounted(() => {
    getDetail();
    getLog();
  })
</script>

<style scoped lang="less">
  .service-after {
    border: 1px solid #eee;
    padding: 10px;
    >div:nth-child(1) {
      width: 400px;
      font-size: 15px;
      font-weight: bold;
      text-align: center;
      line-height: 60px;
      span{color: @theme_color;}
      border-right: 1px solid #eee;
    }
    >div:nth-child(2){
      padding-left: 15px;
      img{vertical-align: top;}
      span{color: #999;}
    }
  }
  .order-card {
    h3 {
      font-weight: normal;
    }
  }

  .reason-list {
    border: 1px solid @light_border_color;
    border-bottom: none;
    color: #666666;
    > div {
      height: 36px;
      line-height: 36px;
      border-bottom: 1px solid @light_border_color;
      padding: 0 20px;
      span:nth-of-type(1) {
        display: inline-block;
        width: 120px;
        text-align: right;
        padding-right: 30px;
        border-right: 1px solid @light_border_color;
      }
      span:nth-of-type(2) {
        padding-left: 30px;
        color: @light_text_color;
      }
    }
  }

  :deep(.arco-steps-vertical .arco-steps-item:not(:last-child)) {
    min-height: 60px;
  }
  :deep(.arco-steps-item-finish .arco-steps-icon) {
    color: @theme_color;
  }
  :deep(.arco-steps-item:not(:last-child).arco-steps-item-finish .arco-steps-item-tail::after) {
    background-color: @theme_color;
  }
</style>
